package com.tf_cut.backend.seller.service;

import com.alibaba.fastjson.JSON;
import com.tf_cut.backend.common.pojo.PageInfo;
import com.tf_cut.backend.common.pojo.Result;
import com.tf_cut.backend.common.service.CommonServiceImpl;
import com.tf_cut.backend.mapper.SellerOrderMapper;
import com.tf_cut.backend.seller.pojo.SellerOrder;
import com.tf_cut.backend.seller.repository.SellerOrderRepository;
import com.tf_cut.backend.seller.vo.SellerOrderExcelVo;
import com.tf_cut.backend.seller.vo.SellerOrderVo;
import com.tf_cut.backend.util.MoneyUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.math.BigDecimal;
import java.util.List;

@Service
@Transactional
@Slf4j
public class SellerOrderServiceImpl extends CommonServiceImpl<SellerOrderVo, SellerOrder, String> implements SellerOrderService {

    @PersistenceContext
    private EntityManager em;
    @Autowired
    private SellerOrderRepository sellerOrderRepository;
    
    @Autowired
	private SellerOrderMapper sellerOrderMapper;

	@Override
	public PageInfo<SellerOrderVo> findListSellerOrder(SellerOrderVo avo) {
		com.github.pagehelper.PageHelper.startPage(avo.getPage(),avo.getRows());
		List<SellerOrderVo> list = sellerOrderMapper.findListSellerOrder(avo);
		com.github.pagehelper.PageInfo<SellerOrderVo> pageinfo = new com.github.pagehelper.PageInfo<>(list);
		
		PageInfo<SellerOrderVo> returnPageInfo = new PageInfo<>();
		returnPageInfo.setPage(pageinfo.getPageNum());//页码
		returnPageInfo.setPageSize(pageinfo.getPageSize());//页面大小
		returnPageInfo.setRows(pageinfo.getList());//分页结果
		returnPageInfo.setRecords((int)pageinfo.getTotal());//总记录数
		returnPageInfo.setTotal(pageinfo.getPages());//总页数
		return returnPageInfo;
	}
	
	


	@Override
	public Result<Boolean> insertSellers(String json) {
		Result<Boolean> result = Result.of(true);
		List<SellerOrderExcelVo> importData = JSON.parseArray(json, SellerOrderExcelVo.class);
		int num = 0;
		try {
			for (SellerOrderExcelVo order : importData) {
	            num++;
	            if (StringUtils.isEmpty(order.getSellerName())) {
	            	result = Result.of(false);
	            	result.setMsg("导入失败！第" + num + "行的商户名称不能为空");
	            	result.setFlag(false);
	                return result;
	            }
	            SellerOrderVo sov = SellerOrderVo.builder()
	            		.importId(order.getImportId())
	            		.sellerId(order.getSellerId())
	            		.sellerName(order.getSellerName())
	            		.serviceId(order.getServiceId())
	            		.serviceName(order.getServiceName())
	            		.serverAmountPoint(MoneyUtil.moneyMulByDecimal(order.getServerAmountPoint(), "100"))
	            		.baseAmountPoint(MoneyUtil.moneyMulByDecimal(order.getBaseAmountPoint(), "100"))
	            		.overAmountPoint(MoneyUtil.moneyMulByDecimal(order.getOverAmountPoint(), "100"))
	            		.stepAmountPoint(MoneyUtil.moneyMulByDecimal(order.getStepAmountPoint(), "100"))
	            		.provideAmount(new BigDecimal(order.getProvideAmount()) )
	            		.realAmount(new BigDecimal(order.getRealAmount()))
	            		.orderType(0)//已提交
	            		.build();
	            
	            if(null != order.getStepAmount())
	            	sov.setStepAmount(new BigDecimal(order.getStepAmount()));
	            
	            if(null != order.getOverAmount())
	            	sov.setOverAmount(new BigDecimal(order.getOverAmount()));
	            
	            super.save(sov);
	        }
		} catch(Exception e) {
			log.error("创建第" + num + "行订单失败。error="+e.getMessage(),e);
			result = Result.of(false);
			result.setMsg("创建第" + num + "行订单失败");
			result.setFlag(false);
		}
        return result;
	}

	@Override
	public Result<Boolean> saveSellers(SellerOrderVo order) {
		Result<Boolean> result = Result.of(true);
		try {
			SellerOrderVo sov = SellerOrderVo.builder()
					.importId(order.getImportId())
					.sellerId(order.getSellerId())
					.sellerName(order.getSellerName())
					.serviceId(order.getServiceId())
					.serviceName(order.getServiceName())
					.serverAmountPoint(MoneyUtil.moneyMul(order.getServerAmountPoint(), new BigDecimal("100")))
					.baseAmountPoint(MoneyUtil.moneyMul(order.getBaseAmountPoint(), new BigDecimal("100")))
					.overAmountPoint(MoneyUtil.moneyMul(order.getOverAmountPoint(), new BigDecimal("100")))
					.stepAmountPoint(MoneyUtil.moneyMul(order.getStepAmountPoint(), new BigDecimal("100")))
					.provideAmount(order.getProvideAmount())
					.realAmount(order.getRealAmount())
					.orderType(0)//已提交
					.build();

			if (null != order.getStepAmount()) {
				sov.setStepAmount(order.getStepAmount());
			}
			if (null != order.getOverAmount()) {
				sov.setOverAmount(order.getOverAmount());
			}
			super.save(sov);
		} catch (Exception e) {
			log.error("saveSellers error:{}", e.getMessage(), e);
			result = Result.of(false);
			result.setMsg("创建订单失败");
			result.setFlag(false);
		}
		return result;
	}

	@Override
	public Result<BigDecimal> calSellerGrantAmount(SellerOrderVo avo) {
		BigDecimal amount = sellerOrderMapper.calSellerOrderAmount(avo);
		Result<BigDecimal> result = Result.of(amount);
		return result;
	}

	@Override
	public void updateSellerOrder(SellerOrderVo sellerOrderVo) {
		sellerOrderMapper.updateSellerOrder(sellerOrderVo);
	}

	@Override
	public SellerOrderVo findSellerOrder(SellerOrderVo sellerOrderVo) {
		return sellerOrderMapper.findSellerOrder(sellerOrderVo);
	}
	
	@Override
	public PageInfo<SellerOrderVo> queryApply(int page, int rows, String sellerName, String serviceName, String startDate,
			String endDate, String orderId) {
		if(!startDate.equals("") && !endDate.equals("")){
			startDate=startDate+" 00:00:00";
			endDate=endDate+" 23:59:59";
		}
		com.github.pagehelper.PageHelper.startPage(page,rows);
        List<SellerOrderVo> list = sellerOrderMapper.queryApply(sellerName,serviceName,startDate,endDate,orderId);
        com.github.pagehelper.PageInfo<SellerOrderVo> pageInfo = new com.github.pagehelper.PageInfo<>(list);
		  PageInfo<SellerOrderVo> returnPageInfo = new PageInfo<>();
	        returnPageInfo.setPage(pageInfo.getPageNum());
	        returnPageInfo.setPageSize(pageInfo.getPageSize());
	        returnPageInfo.setRows(pageInfo.getList());
	        returnPageInfo.setRecords((int) pageInfo.getTotal());
	        returnPageInfo.setTotal(pageInfo.getPages());
	        return returnPageInfo;
	}
	
	
	@Override
	public List<SellerOrderVo> findMoney(String sellerName, String serviceName, String startDate,
			String endDate, String orderId) {
		if(!startDate.equals("") && !endDate.equals("")){
			startDate=startDate+" 00:00:00";
			endDate=endDate+" 23:59:59";
		}
        List<SellerOrderVo> list = sellerOrderMapper.findMoney(sellerName,serviceName,startDate,endDate,orderId);
	        return list;
	}
	
	@Override
	public void updateDetailPaymentStatus(String paymentStatus, String id) {
		sellerOrderMapper.updateDetailPaymentStatus(paymentStatus,id);
	}

	@Override
	public void updateDetailPaymentStatusByOrderId(@Param("paymentStatus")String paymentStatus, @Param("orderId")String orderId) {
		sellerOrderMapper.updateDetailPaymentStatusByOrderId(paymentStatus,orderId);
	}


	
	@Override
	public List<SellerOrderVo> findByProjectInfo(String orderId) {
		return sellerOrderMapper.findByProjectInfo(orderId);
	}




	@Override
	public List<SellerOrderVo> exportGrant(String sellerName, String serviceName, String startDate, String endDate, String orderId) {
		return  sellerOrderMapper.queryApply(sellerName,serviceName,startDate,endDate,orderId);
	}
}
